<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="dialogFormVisible = true"
        >添加</el-button
      >
    </div>
    <el-table :data="tradeInfo.records" border style="width: 100%">
      <el-table-column type="index" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称"> </el-table-column>
      <el-table-column label="品牌LOGO">
        <template v-slot="{ row }">
          <el-image
            :src="row.logoUrl"
            style="width: 100px; height: 80px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row, $index }">
          <el-button size="mini" @click="handleEdit($index, row)" class="mr"
            >编辑</el-button
          >
          <el-button size="mini" type="danger" @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[6, 12, 18, 24]"
      :page-size="pageSize"
      layout=" prev, pager, next, jumper, ->, sizes, total "
      :total="total || tradeInfo.total"
      class="mt"
    >
    </el-pagination>
    <!-- 新增 -->
    <el-dialog :title="tmForm.id?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible" @close="resetForm" :close-on-click-modal="false">
      <el-form :model="tmForm" :rules="rules" ref="tmForm">
        <el-form-item
          label="品牌名称"
          :label-width="formLabelWidth"
          prop="tmName"
        >
          <el-input v-model="tmForm.tmName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="品牌LOGO"
          :label-width="formLabelWidth"
          prop="logoUrl"
        >
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">上传头像图片只能是 JPG 格式，且不超过2M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click="preservation"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import request from "@/api/product/trademark";
import { mapActions, mapState } from "vuex";
export default {
  name: "Trademark",
  data() {
    return {
      pageSize: 6,
      pageNum: 1,
      total: 0,
      dialogTableVisible: false,
      dialogFormVisible: false,
      tmForm: {
        tmName: "",
        logoUrl: "",
        id:""
      },
      formLabelWidth: "120px",
      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        logoUrl: [
          { required: true, message: "请选择品牌LOGO", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    // 编辑
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.tmForm = {
        tmName:row.tmName,
        logoUrl:row.logoUrl,
        id:row.id
      }
    },
    // 删除
    handleDelete(row) {
      this.$confirm(`确定要删除${row.tmName}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await request.getRemove(row.id);
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.tradeActionsTion();
          } catch (error) {
            console.log(error);
            this.$message({
              type: "error",
              message: "删除失败",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 每页条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.tradeActionsTion();
    },
    // 当前页
    handleCurrentChange(val) {
      this.pageNum = val;
      this.tradeActionsTion();
    },
    // 初始化数据
    ...mapActions("trademark", ["tradeActions", "saveActions","updateActions"]),
    // 上传成功
    handleAvatarSuccess(res, file) {
      this.tmForm.logoUrl = res.data;
    },
    // 上传失败
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 上传图片点击保存
    preservation() {
      this.$refs['tmForm'].validate(async(valid) => {
        if (valid) {
          try {
            if(this.tmForm.id){
              await request.getUpdate(this.tmForm)
            }else{

              await request.getSave(this.tmForm);
            }
            this.dialogFormVisible = false;
            this.tradeActionsTion();
            this.$message.success('保存成功')
            this.tmForm = {}
          } catch (error) {
            console.log(error);
          }
        } else {
          return false;
        }
      });
    },
    // 点击取消
    resetForm(){
      this.$refs['tmForm'].resetFields();
      this.dialogFormVisible = false;
      this.tmForm = {}
    },
    // 封装初始请求
    tradeActionsTion() {
      this.tradeActions({ pageNum: this.pageNum, pageSize: this.pageSize });
    },
  },
  computed: {
    ...mapState({
      tradeInfo: (state) => state.trademark.tradeInfo,
    }),
  },
  mounted() {
    this.tradeActions({ pageNum: this.pageNum, pageSize: this.pageSize });
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
